from flask import render_template, g, redirect, request, jsonify, current_app, abort
from info import constants, db
from info.models import Category, News, User
from info.modules.profile import profile_blu
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET


@profile_blu.route('/other_news_list')
def other_news_list():
    page = request.args.get("p", 1)
    other_id = request.args.get("user_id")
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        print(other_id)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    if not other:
        return jsonify(errno=RET.NODATA, errmsg="未查到该用户信息")
    # 查询关注的用户发布过哪些新闻
    try:
        paginate = other.news_list.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        news_lists = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
    other_news_dict_li = []
    for news in news_lists:
        other_news_dict_li.append(news.to_basic_dict())
    data = {
        "news_list": other_news_dict_li,
        "current_page": current_page,
        "total_page": total_page
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """其它用户的页面"""
    user = g.user
    other_id = request.args.get("user_id")
    if not other_id:
        abort(404)
    # 查询被关注用户的信息
    other = None
    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)
    # 显示用户是否关注过作者
    is_followed = False
    if other and user:
        if other in user.followed:
            is_followed = True
    data = {
        "is_followed": is_followed,
        "other": other.to_dict(),
        "user": user.to_dict() if user else None
    }
    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    """个人中心关注页面"""
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    follows_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    follows_dict_li = []
    is_followed = False
    for follow in follows_list:
        follows_dict_li.append(follow.to_dict())
        if follow and user:
            if follow in user.followed:
                is_followed = True
    data = {
        "follows_dict_li": follows_dict_li,
        "current_page": current_page,
        "total_page": total_page,
        "is_followed":is_followed
    }
    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list')
@user_login_data
def user_news_list():
    """
    获取当前用户发布的新闻及状态
    :return:
    """
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    # 分页查询
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_dict_li
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=["get", "post"])
@user_login_data
def news_release():
    """
    用户发布新闻
    1.获取参数,新闻标题title、来源source、摘要digest、索引图片index_image、分类id、内容
    2.校验参数
    3.初始化新闻模型
    4.保存
    5.返回响应
    :return:
    """
    if request.method == "GET":
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        categories_dicts = []
        for category in categories:
            cate_dict = category.to_dict()
            categories_dicts.append(cate_dict)
        # 移除`最新`分类
        categories_dicts.pop(0)
        return render_template('news/user_news_release.html', data={"categories": categories_dicts})
    title = request.form.get("title")
    source = "个人发布"
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    category_id = request.form.get("category_id")
    print([title, source, digest, index_image, content, category_id])
    # 校验
    if not all([title, source, digest, index_image, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
    news = News()
    news.title = title
    news.category_id = category_id
    news.content = content
    news.digest = digest
    news.source = source
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.user_id = g.user.id
    news.status = 1
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg='OK')


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    """
    个人收藏展示
    1.获取参数，请求的页数p(默认是第一页)
    2.校验参数
    3.查询数据
    4.返回响应
    :return:
    """
    page = request.args.get("p", 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
    user = g.user
    news_list = []
    current_page = 1
    total_page = 1
    # 分页查询
    try:
        paginate = user.collection_news.paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "current_page": current_page,
        "total_page": total_page,
        "collections": news_dict_li
    }
    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login_data
def pass_info():
    """
    修改密码的逻辑
    1.获取参数，原密码old_password、新密码new_password
    2.校验参数
    3.查询用户密码数据进行修改
    4.返回响应
    :return:
    """
    if request.method == "GET":
        return render_template('news/user_pass_info.html')
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")
    if not all([old_password, new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    user = g.user
    # 检测原密码与用户输入是否一致
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='原密码错误')
    # 设置密码
    user.password = new_password
    return jsonify(errno=RET.OK, errmsg='OK')


@profile_blu.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    """
    上传头像功能的实现
    1.获取参数，头像文件信息avatar
    2.校验参数
    3.保存头像
    4.返回响应
    :return:
    """
    user = g.user
    if request.method == "GET":
        return render_template('news/user_pic_info.html', data={"user": user.to_dict()})
    try:
        # 取到上传的图片
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 上传图片到七牛云(第三方云存储平台)
    try:
        key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传头像失败')
    # 保存头像地址
    user.avatar_url = key
    return jsonify(errno=RET.OK, errmsg='OK', data={"avatar_url": constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    """
    渲染个人中心
    1.接受参数，用户昵称、签名、性别
    2.校验参数
    3.保存用户数据
    4.返回响应
    :return:
    """
    user = g.user
    if request.method == "GET":
        return render_template('news/user_base_info.html', data={"user": user.to_dict()})
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    if gender not in ['MAN', 'WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    return jsonify(errno=RET.OK, errmsg='OK')


@profile_blu.route('/info')
@user_login_data
def user_info():
    """渲染基本框架"""
    user = g.user
    if not user:
        return redirect('/')
    data = {
        "user": user.to_dict()
    }
    return render_template('news/user.html', data=data)
